// LicenseChecker.cpp: implementation of the LicenseChecker class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "kwservercore.h"
#include "LicenseChecker.h"
#include "ServerConfiguration.h"
#include "TimeManager.h"

#include "CommonLib\ValueConverter.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LicenseChecker::LicenseChecker()
{
	std::vector<std::string> vecMACAddress;
	std::vector<std::string> vecDescription;
	LicenseManager::GetLocalMACAddress(vecMACAddress, vecDescription);
	const std::string& strMACAddress = ServerConfiguration::Instance()->m_strMACAddress;
	if (std::find(vecMACAddress.begin(), vecMACAddress.end(), strMACAddress) != vecMACAddress.end())
	{
		m_lm.SetMacAddrString(strMACAddress);
	}
	else if (vecMACAddress.size() > 0)
	{
		m_lm.SetMacAddrString(vecMACAddress[0]);
	}
	else
	{
		m_lm.SetMacAddrString("000000000000");
	}
	m_lm.ApplyKey(ServerConfiguration::Instance()->m_strLicenseKey);
}

LicenseChecker::~LicenseChecker()
{
}

bool LicenseChecker::IsValid() const
{
	std::string strExpiration;
	m_lm.GetExpirationString(strExpiration);
	std::string strEvaluationPeriod;
	m_lm.GetEvaluationPeriodString(strEvaluationPeriod);

	return strExpiration != "NA" && strEvaluationPeriod != "NA";
}

bool LicenseChecker::IsExpiry() const
{
	bool bExpiry = true;

	if (IsValid())
	{
		std::string strExpiration;
		m_lm.GetExpirationString(strExpiration);
		if (strExpiration != "Forever")
		{
			std::vector<int> vecDate;
			ValueConverter::StringTokenizer(strExpiration.c_str(), "/", vecDate);
			CTime time(vecDate[2], vecDate[0], vecDate[1], 10, 0, 0);
			if (TimeManager::Instance()->GetTime() < time)
			{
				bExpiry = false;
			}
		}
		else
		{
			bExpiry = false;
		}
	}

	return bExpiry;
}

CString LicenseChecker::GetMACAddress() const
{
	std::string strMACAddr;
	m_lm.GetMacAddrString(strMACAddr);
	return strMACAddr.c_str();
}

CString LicenseChecker::GetLicenseKey() const
{
	std::string strLicenseKey;
	m_lm.GetKeyString(strLicenseKey);
	return strLicenseKey.c_str();
}